<template>
  <div class="wirte">
    <!-- # 标题 -->
    <div class="tabbar" style="{ background: white; }">
        <span>小小笔记本</span>
        <div class="right_wrappered">
            <router-link class="selection" to="/"><i class="el-icon-s-promotion "></i>首页</router-link>
            <div class="selection img_wrapper">
                <img class="head_img selection" :src="imgUrl" alt="">
                &nbsp;{{ name }}
            </div>
        </div>
    </div>
    <div class="div_out_wrapper">
      <div class="drop div_inner_wrapper">
        <!-- 文章标题 -->
        <div class="_title">
            <router-link style="margin-left: 20px;" to=""> &nbsp; 文章标题：</router-link>
            <el-input
                style="width: 280px; margin-left: 5px;"
                type="text"
                placeholder="请输入文章标题"
                v-model="title"
                maxlength="40"
                show-word-limit
            >
            </el-input>
            <button class="commit_button" type="primary" @click="mask = true">提交文章</button>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;
                字数：{{ content.length }} &nbsp; &nbsp;字</span>
        </div>
          <!-- 图片上传组件辅助-->
        <el-upload
            class="avatar-uploader"
            :action="serverUrl"
            name="img"
            :headers="header"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload">
        </el-upload>
        <!-- 富文本编辑器 -->
        <quill-editor 
            class="editor"
            v-model="content"
            ref="myQuillEditor" 
            :options="editorOption" 
            @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
            @change="onEditorChange($event)">
        </quill-editor> 
      </div>
    </div>
    <!-- 遮罩层 -->
    <el-dialog :visible.sync="mask" width="40%">
      <div class="demoTwo">
          <ul v-if="!display">
            <li class="li_warpper">
              <span>文章标题：</span>
              <el-input
                id="inner_input"
                placeholder="请返回文章中输入标题！"
                v-model="title"
                :disabled="true">
              </el-input>
            </li>
            <li class="li_warpper">
              <span>内容概述：</span>
              <el-input
                id="inner_input"
                placeholder="请输入概述(二级标题).."
                v-model="second_title">
              </el-input>
            </li>
            <li>
              <span>文章类别：</span>
               <el-select v-model="value" clearable placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.kind_num"
                    :label="item.kind_name"
                    :value="item.kind_num">
                  </el-option>
                </el-select>
              <a @click="display=true" style="margin-left: 20px;" href="#">
                新增类别?</a>
            </li>
            <!-- 添加封面 -->
            <li class="li_warpper down_it">
              <span>展示封面：</span>
              <el-upload
                :action=action_url
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-success="up_success">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </li>
            <li class="down_it_it">
                <el-button @click="commit_it()" class="write_button" type="primary">发布文章</el-button>
                <el-button @click="commit_it_toAdit()" class="write_button" type="info">保存草稿</el-button>
                <el-button @click="mask=false" class="write_button" type="danger">&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button>
            </li>
          </ul>
          <ul v-if="display">
            <li class="li_warpper">
              <span>新增类别:</span>
              <el-input
                id="inner_input"
                placeholder="请输入类别名称"
                v-model="newkind">
              </el-input>
              <div @click="add_newType()" style="color:#2E9AFE; width: 100px; height: 40px; line-height: 40px;">新增类别</div>
              <div @click="display=false" style="color:#FF0040; width: 50px; height: 40px; line-height: 40px;">取消</div>
            </li>
          </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { host } from '../../network/color_check.js';
import Cookies from 'js-cookie';
import ImageResizes from 'quill-image-resize-module'
Quill.register('modules/imageResize', ImageResizes)
import Qs from 'qs'
import axios from 'axios';

export default {
    name: 'write',
    data() {
        return {
            title: '',
            second_title: '',
            imgUrl: '',
            name: '',
            action_url: '',
            display: false,
            
            newkind: '',
            options: [],
            value: '',  // 
            // 上传封面。
            dialogImageUrl: '',
            dialogVisible: false,

            message: {
              'image_url': '',
              'title': '',
              'status': 1,
              'kind': 0,
              'content': '',
              'second_title': '',
            },  // 文章的详细情况

            mask: false,
            // 富文本编辑器
            serverUrl:  host.url+"/artical/addimage.htm", // 这里写你要上传的图片服务器地址
            header: {},
            quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
            content: "",
            editorOption: {
                theme: 'snow',
                placeholder: '说点什么吧...',
                modules: {
                    toolbar: {
                        handlers: {
                            image: function(value) {
                                if (value) {
                                // 触发input框选择图片文件
                                document.querySelector(".avatar-uploader input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                        container: [
                            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
                            ["blockquote", "code-block"], // 引用  代码块
                            [{ header: 1 }, { header: 2 }], // 1、2 级标题
                            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
                            [{ script: "sub" }, { script: "super" }], // 上标/下标
                            [{ indent: "-1" }, { indent: "+1" }], // 缩进
                            // [{'direction': 'rtl'}],                         // 文本方向
                            [{ size: ["small", false, "large", "huge"] }], // 字体大小
                            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
                            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                            [{ font: [] }], // 字体种类
                            [{ align: [] }], // 对齐方式
                            ["clean"], // 清除文本格式
                            ["link", "image", "video"] // 链接、图片、视频
                        ],
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: "black",
                            border: "none",
                            color: "white",
                        },
                        modules: ["Resize", "DisplaySize", "Toolbar"],
                    },
                },
            }
        }
    },
    created() {
        // 获取头像
        this.imgUrl= '';
        this.action_url = host.url+"/artical/add_artical_cover.htm";
        this.getImgUrl();
        // 发送请求接收文章类别列表
        axios({
            url:  host.url+'/kind/kinds.html',
            method: 'get',
        })
        .then(suc =>{
            this.options = suc.data.kind_list;
        })
        .catch(fail => {
          this.$message.error("获取文章类别列表失败了..");
        });
    },
    methods: {
        // 添加待编辑文章
        commit_it_toAdit() {
          this.message.status = 0;
          this.commit_it();
        },
        // 添加文章类别
        add_newType() {
            this.$confirm('确认添加新的文章类别嘛?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                if(this.newkind === '') {
                    this.$message({
                      type: 'error',
                      message: '类别名不可以为空..'
                    });  
                    reutrn ;
                }
                // 发送axios请求
                axios({
                    url:  host.url+'/kind/add_kind.html',
                    method: 'post',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
                    data: {
                        kind_name: this.newkind,
                    },
                    transformRequest: [function (data) {
                        data = Qs.stringify(data);
                        return data;
                    }],
                })
                .then(suc =>{
                    if ( suc.data.code === 200 ) {
                      this.$message({
                        type: 'success',
                        message: '添加成功!'
                      });
                      axios({
                          url:  host.url+'/kind/kinds.html',
                          method: 'get',
                      })
                      .then(suc =>{
                          this.options = suc.data.kind_list;
                      })
                      .catch(fail => {
                        this.$message.error("获取文章类别列表失败了..");
                      });
                    } else {
                      this.$message({
                        type: 'error',
                        message: '出错了!'
                      })
                    }
                    this.display = !this.display;
                })
                .catch(fail => {
                    console.log(fail);
                    this.$message({
                      type: 'error',
                      message: '新增失败了..'
                    });  
                });
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消添加文章类别'
                });          
              });
        },
        // 提交文章
        commit_it() {
          if (!this.name) {
              this.$message.warning("宁还没有登录，请登录后，记得保存记录啊..");
              return;
          }
          if (this.name !=  'lixun' && this.name != 'leslie') {
              this.$message.warning("宁不是站长啊，请联系站长后再重试..");
              return;
          }
          // 如果缺少必传参数
          if(!this.second_title || !this.message.image_url || !this.message.title || !this.message.kind || !this.message.content) {
              this.$message.error("缺少必传参数！请注意图片和标题！");
              return ;
          }
          this.$confirm('确认新增文章嘛?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                  var data = JSON.stringify(this.message);
                  axios({
                      url:  host.url+'/artical/addartical.htm',
                      method: 'post',
                      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
                      data: {
                          form_data: data,
                      },
                      transformRequest: [function (data) {
                          data = Qs.stringify(data);
                          return data;
                      }],
                  })
                  .then(suc =>{
                      if( suc.data.code === 200 ) {
                          this.$message({
                            type: 'success',
                            message: '提交文章成功了!'
                          }); 
                          // 返回index页面
                          this.$router.replace({path: '/'});
                      } else {
                        this.$message({
                            type: 'error',
                            message: '数据库出错了...'
                          });
                      }
                  })
                  .catch(fail => {
                      this.$message({
                        type: 'error',
                        message: '提交文章出错了..'
                      });     
                  });
              })
              .catch( () => {
                  this.$message({
                  type: 'info',
                  message: '已取消提交文章'
                });     
              })
        },
        // 遮罩层里面的上传图片成功了
        up_success(res) {
          this.message.image_url = res.url;
          this.message.content = this.content;
          this.message.kind = this.value;
          this.message.status = 1;
          this.message.title = this.title;
          this.message.second_title = this.second_title;
          this.message.writer = this.name;
          this.message.writer_img_url = this.imgUrl;     
        },
        handlePictureCardPreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        // 下面3个都是富文本编辑器的事件函数
        onEditorBlur() {
        //失去焦点事件
        },
        onEditorFocus() {
        //获得焦点事件
        },
        onEditorChange() {
        //内容改变事件
            this.$emit("input", this.content);
        },
        // 富文本图片上传前
        beforeUpload() {
        // 显示loading动画
            this.quillUpdateImg = true;
        },
        // 文件上传成功。
        uploadSuccess(res, file) {
            // res为图片服务器返回的数据
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 如果上传成功
            if (res.code == 200) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片  res.url为服务器返回的图片地址
                quill.insertEmbed(length, "image", res.url);
                // 调整光标到最后
                quill.setSelection(length + 1);
            } else {
                this.$message.error("图片插入失败");
            }
            // loading动画消失
            this.quillUpdateImg = false;
        },
        // 富文本图片上传失败
        uploadError() {
            // loading动画消失
            this.quillUpdateImg = false;
            this.$message.error("图片插入失败");
        },
        // 获取头像的地址
        getImgUrl() {
            var a = Cookies.get();
            // 遍历cookie的值
            for(let key in a){
                // console.log(key);
                if( a[key] === '1' ) {
                this.not_Login = false;
                this.name = key;
                // console.log('name: ' + this.name);
                break;
                }
            }
            // 查找cookie中有没有url的链接
            if( Cookies.get('img_url') ) {
                this.imgUrl = Cookies.get('img_url');
                
                return ;
            }
        },
    }
};
</script> 

<style>
.write_button {
  margin-left: 20px;
  margin-right: 20px;
}
.down_it_it {
  margin-top: 125px;
  margin-left: 70px;
}
.el-input__inner {
    background-color:white;
}
.down_it {
  margin-top: 20px;;
}
.el-select {
  width: 330px;
  margin-left: 10px;
}
.li_warpper {
  height: 60px;
  display: flex;
}
.li_warpper span {
  width: 100px;
  height: 60px;
  line-height: 40px;
}
.li_warpper #inner_input {
  width: 330px;
}
.demoTwo {
  width: 100%;
  height: 400px;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}
.div_inner_wrapper {
  width: 55%;
}
.div_out_wrapper {
  display: flex;
  justify-content: space-around;
}
.editor {
  line-height: normal !important;
  height: 500px;
}
._title {
    font-size: 16px;
    display: flex;
    /* justify-content: space-between; */
    width: 100%;
    height: 45px;
    line-height: 45px;
    background: #F2F2F2;
}
.commit_button {
    height: 35px;
    line-height: 35px;
    width: 80px;
    text-align: center;
    background: #2E9AFE;
    color: white;
    border-radius: 5px;
    border: 0px;
    margin-top: 5px;
    margin-left: 30px;
}
.right_wrappered {
    display: flex;
    width: 20%;
    justify-content: space-evenly;
}
.img_wrapper {
    margin-right: 20px;
}
.space_box {
    width: 35%;
    height: 550px;;
    margin: 70px auto;
}

.drop {
  padding-top: 50px;
}
.editor {
  line-height: normal !important;
  height: 800px;
}

.ql-snow .ql-tooltip[data-mode=link]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode=video]::before {
    content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
  content: '10px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
  content: '18px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
  content: '32px';
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: '文本';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: '标题1';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: '标题2';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: '标题3';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: '标题4';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: '标题5';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: '标题6';
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: '标准字体';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before {
  content: '衬线字体';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before {
  content: '等宽字体';
}
</style>
